package cn.jbit.test.io.nio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/10
 */
public class NioClientHandler implements Runnable{

    private  String  host;//主机名
    private  int port;//端口号
    private Selector selector; //多路复用器
    private SocketChannel socketChannel; //客户端通道
    private  volatile  boolean stop=false;

    public NioClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try{
            selector=Selector.open();
            socketChannel=SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }


    @Override
    public void run() {

        try {
            doConnect();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (!stop){
            try {
                int wait=selector.select(1000);
                if (wait==0){
                    continue;
                }
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;

                while (it.hasNext()){
                        key=it.next();
                        it.remove();
                        try {
                            handle(key);
                        }catch (Exception e) {
                                if (key!=null){
                                    key.cancel();
                                    if (key.channel()!=null){
                                        key.channel().close();
                                    }
                                }
                        }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        if (selector!=null){
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //客户端处理服务端的请求信息
    private  void  handle(SelectionKey key) throws IOException {

        if (key.isValid()){

            SocketChannel sc= (SocketChannel) key.channel();

            if (key.isConnectable()){
                if (sc.finishConnect()){
                    sc.register(selector,SelectionKey.OP_READ);
                    doWrite(sc);
                }else {
                    System.exit(1);
                }
            }
            if (key.isReadable()){
                ByteBuffer readBuffer=ByteBuffer.allocate(1024);
                int read=sc.read(readBuffer);
                if(read>0){
                    readBuffer.flip();
                    byte[] bytes=new byte[readBuffer.remaining()];

                    readBuffer.get(bytes);
                    System.out.println("res"+new String(bytes,"UTF-8"));


                }else if(read<0){
                    key.cancel();
                    sc.close();
                }

            }
        }


    }

    //客户端发起连接的方法
    private  void  doConnect() throws IOException {
        if (socketChannel.connect(new InetSocketAddress("localhost",8080))){
                socketChannel.register(selector, SelectionKey.OP_READ);
                doWrite(socketChannel);
        }else {
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }

    //客户端写事件
    private void doWrite(SocketChannel socketChannel) throws IOException {
        Scanner sc=new Scanner(System.in);
        String input=sc.next();
        byte[] bytes=input.getBytes();
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        byteBuffer.put(bytes);
        byteBuffer.flip();
        socketChannel.write(byteBuffer);
        if (!byteBuffer.hasRemaining()){
            System.out.println("写入完成");
        }
    }


}
